const crypto = require('crypto');

class RsaEncryptUtil {
    // 公钥（Base64格式，无需头尾）
    static PUBLIC_KEY_BASE64 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA9OQ+jUMymb+HXLZ2JyCNt0yESf9+jPUxHDwsgvBTt51ZT/vf9TcAim+NlWyg5nM1p+o7TNqhjypbqFkIWkeISooTrUPlnkiuCB3iGeoVirGNXrvAXxt4L8zfkZsr7kNOHFbLldVRZnw6IwB0oz89EorJt6/KoUVk+cpCsRFLhY6HmMFWPzJ+w3Cde032dTem9rAJsZH5bfzcyenJ8Ymj/aOX79RCrX8dUKiDHyOLbYXlvhLqtTLpAFmdYMfv5qu+YGsDSGRLYXnMjR7SGNy/Ju37JdoFko7FhobD8hgLBymL6+EW/hMNjSQyhNhV3RrVKqQTjAcX+FlxD1PF3bFKoQIDAQAB";

    /**
     * 加密传输参数（以 JSON 格式）
     *
     * @param {string} appKey    应用Key
     * @param {string} timestamp 时间戳
     * @param {string} account   账户
     * @param {string} password  密码
     * @return {string} Base64编码的加密密文
     */
    static encrypt(appKey, timestamp, account, password) {
        try {
            // 封装参数为对象
            const data = {
                account: account,
                password: password,
                timestamp: timestamp,
                appKey: appKey
            };
            
            // 转为 JSON 字符串
            const json = JSON.stringify(data);
            
            return this.encryptJson(json);
        } catch (error) {
            throw new Error(`加密失败：${error.message}`);
        }
    }

    /**
     * 直接加密JSON字符串
     *
     * @param {string} json JSON字符串
     * @return {string} Base64编码的加密密文
     */
    static encryptJson(json) {
        try {
            // 构造完整的PEM格式公钥
            const publicKeyPem = `-----BEGIN PUBLIC KEY-----\n${this.PUBLIC_KEY_BASE64}\n-----END PUBLIC KEY-----`;
            
            // 使用RSA公钥加密
            // padding: crypto.constants.RSA_PKCS1_PADDING 对应Java的PKCS#1 Padding
            const encrypted = crypto.publicEncrypt({
                key: publicKeyPem,
                padding: crypto.constants.RSA_PKCS1_PADDING
            }, Buffer.from(json, 'utf8'));
            
            // 返回Base64编码的结果
            return encrypted.toString('base64');
        } catch (error) {
            throw new Error(`加密失败：${error.message}`);
        }
    }

    /**
     * 生成当前时间戳
     * @return {string} 时间戳字符串
     */
    static getCurrentTimestamp() {
        return Date.now().toString();
    }

    /**
     * 生成ISO格式时间戳
     * @return {string} ISO时间戳字符串
     */
    static getCurrentISOTimestamp() {
        return new Date().toISOString();
    }
}

// 使用示例
function main() {
    try {
        const appKey = "third_xyz";
        // 获取当前时间戳 - 方式1：毫秒时间戳
        const timestamp = RsaEncryptUtil.getCurrentTimestamp();
        const account = "admin";
        const password = "test";
        
        console.log("原始参数:");
        console.log(`appKey: ${appKey}`);
        console.log(`timestamp: ${timestamp}`);
        console.log(`account: ${account}`);
        console.log(`password: ${password}`);
        console.log();
        
        // 方式1：使用参数加密
        const encryptedResult1 = RsaEncryptUtil.encrypt(appKey, timestamp, account, password);
        console.log("加密结果1 (参数方式):");
        console.log(encryptedResult1);
        console.log();
        
        // 方式2：直接加密JSON字符串
        const jsonData = JSON.stringify({
            account: account,
            password: password,
            timestamp: timestamp,
            appKey: appKey
        });
        const encryptedResult2 = RsaEncryptUtil.encryptJson(jsonData);
        console.log("加密结果2 (JSON字符串方式):");
        console.log(encryptedResult2);
        console.log();
        
        // 使用ISO时间戳的示例
        const isoTimestamp = RsaEncryptUtil.getCurrentISOTimestamp();
        const encryptedResult3 = RsaEncryptUtil.encrypt(appKey, isoTimestamp, account, password);
        console.log("加密结果3 (ISO时间戳):");
        console.log(encryptedResult3);
        
    } catch (error) {
        console.error("加密过程中发生错误:", error.message);
    }
}

// 如果直接运行此文件，则执行示例
if (require.main === module) {
    main();
}

// 导出类供其他模块使用
module.exports = RsaEncryptUtil;